<template>
  <ul class="list-wrapper">
    <li class="product-list-item goods-item-border" v-for="(goodsItem, goodsIndex) in formatGoodsList" :key="goodsIndex">
      <div class="goods-image">
        <router-link :to="{name: 'productDetail', params: {commodityID: goodsItem.goodsId}}">
          <img class="list-img" :src="prefixImg + goodsItem.image" :alt="goodsItem.detail" @error="catchErrorImage($event)">
        </router-link>
      </div>
      <div class="goods-info">
        <router-link
        :to="{name: 'productDetail', params: {commodityID: goodsItem.goodsId}}"class="goods-detail">
          <span v-html="goodsItem.detail"></span>
          <span class="activeTag" v-if="+goodsItem.activityId > 0">活动</span>
        </router-link>
        <router-link
          :to="{name: 'productDetail', params: {commodityID: goodsItem.goodsId}}"
        tag="p" class="goods-name" v-html="`${goodsItem.goodsName} ${goodsItem.brandName} ${goodsItem.other ? goodsItem.other : ''}`"></router-link>
        <div class="goods-price">
          <template v-if="loginStatus === 1">
            <span class="current-price">{{goodsItem.price}}元</span>
            <span class="old-price" v-if="+goodsItem.discountPrice > 0">￥{{goodsItem.discountPrice}}</span>
          </template>
          <span class="current-price" v-else-if="loginStatus === 4">登录后查看</span>
          <span class="current-price" v-else>审核通过后查看</span>
        </div>
      </div>

      <div class="goods-right-order">
        <div class="goods-stock">
          <div v-if="goodsItem.stockLimit">
            (剩余{{goodsItem.stock}}件)
          </div>
          <div v-else="goodsItem.stock">有货</div>
          <!-- <div v-else>
            <span
              class="color-blue pointer"
              @click.prevent="showConsult(goodsItem)"
              v-if="goodsItem.consultStatus === 0"
            >（查询库存）</span>
            <span class="color-gray66" v-else>{{goodsItem.inventoryStatusDesc}}</span>
          </div> -->
        </div>
        <div class="input-number-box">
          <el-input-number
            class="goods-input-number"
            @keydown.110.native.prevent=""
            size="mini "
            :disabled="loginStatus !==1 "
            :key="goodsItem.id"
            v-model="goodsItem.number"
            :min="0"
            :max="goodsItem.personalLimited ? goodsItem.lastPersonalLimitNum : goodsItem.maxNum"
            :ref="'pro_' + goodsIndex"
            :step="goodsItem.packingNum"
            @change="limitProNum($event, goodsIndex, goodsItem.packingNum, goodsItem)"
            >
          </el-input-number>
          <p v-show="goodsItem.packingNum !== 1" class="packingNum">包装数：{{goodsItem.packingNum}}</p>
        </div>
        <el-button type="primary" size="medium" class="goods-btn-add" @click="addShopcart(goodsItem.id, goodsItem.number, goodsIndex)">加入采购清单</el-button>
        <!-- <div class="goods-right-packing" v-show="goodsItem.packingNum !== 1">
          包装数：{{goodsItem.packingNum}}
        </div> -->
      </div>
    </li>
  </ul>
</template>

<script>
import _ from 'lodash'
import { changeProNumber } from '@/service/get-data'
import { mapState, mapActions } from 'vuex'
import { prefixImg } from '@/tool/index'
import { getCookie } from '@/config/mUntils'
import { InputNumber, Button } from 'element-ui'
import { eventBus } from '@/tool/events-bus'

export default {
  name: 'TypeProduct',
  components: {
    elInputNumber: InputNumber,
    elButton: Button
  },
  props: {
    activityList: {
      type: Array || Object
    }
  },
  computed: {
    ...mapState({
      shopcartId: state => state.shopcart.shopCartId
    }),
    authUserMethod () {
      if (!this.Token) {
        this.$confirm('此操作需要登录,是否前去登录', '提示').then(() => {
          this.$router.push({name: 'Login', query: { redirect: this.$route.fullPath }})
        }).catch(() => {
          console.log('未登录')
        })
        return false
      } else if (this.Exam === 3) {
        this.$store.commit('EXAMNODO', true)
        return false
      } else if (this.Exam === 2) {
        this.$store.commit('EXAMFAIL', true)
        return false
      } else if (this.Exam === 0) {
        this.$message.error('您的企业信息还在审核中,商品不能加入购物车,我们尽快给您审核.')
        return false
      } else {
        return true
      }
    },
    Token () {
      return getCookie('Token')
    },
    Exam () {
      return parseInt(getCookie('Exam'))
    },
    loginStatus () {
      return this.$store.getters.loginStatus
    }
  },
  data () {
    return {
      prefixImg,
      formatGoodsList: this.activityList
    }
  },
  methods: {
    ...mapActions(['fetchCartList']),
    catchErrorImage (e) {
      e.target.src = require('img/newload.png')
    },
    limitProNum (value, index, step, objitem) {
      this.formatGoodsList = [...this.formatGoodsList] // 强制vue监听变化
      this.debounceLimitProNum(value, index, step, objitem)
    },
    debounceProNum () {
      this.debounceLimitProNum = _.debounce(function (value, index, step, objitem) {
        let result = this.authUserMethod
        if (!result) {
          return false
        }
        if (value === 0) return
        let surplusNum // 去掉购物车数量的剩余可购买数量
        let shopcatNum = 0
        // 如果不存在id请求购物车
        if (!this.shopcartId) {
          this.fetchCartList()
          this.shopcartId = this.$store.state.shopcart.shopCartId
        }
        let lastNum = value % step
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        if (lastNum !== 0) {
          this.$message(`您当前选择的商品是${step}件一起采购哦`)
          // return
        }

        // 个人限购 商品不限购
        if (objitem.personalLimited) {
          this.limitArr.map((limitItm, limitInd) => {
            if (objitem.id === limitItm.pid) {
              shopcatNum = limitItm.num
            }
          })
          surplusNum = objitem.lastPersonalLimitNum - shopcatNum
          // 购物存货和限购数量一样 或 个人限购剩余数量为0
          if (surplusNum === 0 || objitem.lastPersonalLimitNum === 0) {
            this.$nextTick(() => {
              this.$refs[`pro_${index}`][0].setCurrentValue(0)
            })
            this.$message(`抱歉,此商品限购期间每人限购${objitem.personalLimitNum}件,您已达此商品的添加上限`)
          // 输入数量大于可购数量
          } else if (surplusNum > 0 && leftNum > surplusNum) {
            if (objitem.stockLimit && surplusNum > objitem.stock) {
              this.$nextTick(() => {
                this.$refs[`pro_${index}`][0].setCurrentValue(objitem.stock)
                // this.temporaryCart[objitem.id].num = objitem.stock
                // this.$refs[`pro_${index}`].setCurrentValue(objitem.stock)
              })
              this.$message(`您的选购数量已达库存数量`)
              return
            } else {
              this.$nextTick(() => {
                this.$refs[`pro_${index}`][0].setCurrentValue(surplusNum)
                // this.temporaryCart[objitem.id].num = surplusNum
                // this.$refs[`pro_${index}`].setCurrentValue(surplusNum)
              })
              this.$message('您的选购数量已达上限')
              return
            }
          }
        }

        // 商品限购
        if (objitem.stockLimit && leftNum > objitem.stock) {
          this.$message('您的选购数量已达库存数量')
          this.$nextTick(() => {
            this.$refs[`pro_${index}`][0].setCurrentValue(objitem.stock)
          })
          leftNum = objitem.stock
        } else {
          this.$nextTick(() => {
            this.$refs[`pro_${index}`][0].setCurrentValue(leftNum)
            // this.temporaryCart[objitem.id].num = leftNum
            // this.$refs[`pro_${index}`].setCurrentValue(leftNum)
          })
        }
      }, 100, {leading: true, trailing: false})
    },
    debounceShopcart () {
      this.addShopcart = _.debounce(async function (id, number, skuIndex) {
        const result = this.authUserMethod
        if (!result || !number) return
        const vm = this
        let res = await changeProNumber(this.shopcartId, id, '', number, 0)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.formatGoodsList[skuIndex].number = 0
          this.$nextTick(() => {
            vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
          })
          this.$emit('refresh')
          this.fetchCartList() // 更新购物车列表
          eventBus.$emit('show:pop')
        } else {
          this.$message.error({
            message: res.data.resultMsg
          })
        }
      }, 300, {leading: true, trailing: false})
    }
  },
  mounted () {
    // const _this = this

    this.debounceShopcart()
    this.debounceProNum()
    // this.$nextTick(() => {
    //   _this._initData()
    // })
  },
  watch: {
    activityList (newVal) {
      console.log('watch')
      this.formatGoodsList = [...newVal]
    }
  }
}
</script>

<style lang="scss" scoped>
  .activeTag{
    height:16px;
    line-height: 16px;
    vertical-align: middle;
    display: inline-block;
    border-radius:4px;
    border:1px solid rgba(255,115,0,1);
    font-size: 10px;
    padding: 0 3px;
    color: #FF7300;
  }
  .product-list-item{
    font-size: 0;
    padding: 10px 20px 10px 30px;
    position: relative;
    height: 100px;
    margin-top: 10px;
    background: #fff;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;

    .goods-image{
      display: inline-block;
      vertical-align: top;
      width: 79px;
      height: 79px;
      // border: 1px solid #e6e6e6;
      position: relative;
      img{
        width: 100%;
        // height: 90px;
      }
    }
    .goods-info{
      display: inline-block;
      vertical-align: top;
      width: 280px;
      margin: 0 120px 0 10px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      .goods-detail{
        display: block;
        font-size: 14px;
        color: #222;
        margin-top: 5px;
        height: 20px;
        line-height: 20px;
        overflow: hidden;
      }
      .goods-name{
        font-size: 12px;
        color: #888;
        margin: 5px 0;
      }
      .goods-price{
        display: inline-block;
        vertical-align: top;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        margin-top: 15px;
        font-size: 14px;
        .current-price{
          color: #f03a58;
          font-size: 16px;
        }
        .old-price{
          color: silver;
          font-size: 16px;
          text-decoration: line-through;
        }
      }
    }
    .goods-stock{
      display: inline-block;
      vertical-align: top;
      padding-top: 9px;
      color: #666;
      font-size: 14px;
      line-height: 16px;
      vertical-align: middle;
      margin-right: 20px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      vertical-align: top;
    }
    .input-number-box{
      display: inline-block;
      text-align: center;
      vertical-align: top;
    }
    .packingNum{
      color: #666;
      font-size: 12px;
      line-height: 2em;
    }
    .goods-right-order{
      float: right;
      position: relative;
      display: inline-block;
      vertical-align: top;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin-top: 25px;
      font-size: 14px;
    }
    .goods-input-number{
      width: 100px;
      margin-top: 3px;
      vertical-align: top;
    }
    .goods-btn-add{
      margin-left: 20px;
      color: #333;
      vertical-align: top;
    }
    .goods-right-packing{
      position: absolute;
      bottom: -18px;
      font-size: 12px;
      color: #B0B0B0;
      padding-left: 108px;
    }
  }
</style>
